<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  

<input type="file" onchange="change(this)">
<img id="avatar" width="100" height="100">

<script>
function change( input ){
  var img = input.files[0];
  if( !/\.(jpg|png|svg|webp)$/.test( img.name ) ){
    alert('请上传图片格式！(jpg、png、svg、webp)');
    input.value = '';
    return;
  }
  var reader = new FileReader();
  //onload 表示读取完毕 异步操作 h
  reader.onload = function(){
    //reader.result 得到base64编码
    console.log( reader.result );
    avatar.src = reader.result;
  }
  //将图片文件读取为base64编码的图片
  reader.readAsDataURL( img );
  console.log('hello');
}
</script>

</body>
</html>